package com.itboye.ihomebank.activity.me;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.util.alipay.OrderInfoUtil2_0;
import com.itboye.ihomebank.util.alipay.PayResult;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.HuanKuansBean;
import com.itboye.ihomebank.bean.PayInfo;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.JinRongPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DoubleUtil;
import com.itboye.ihomebank.util.TimeFormat;
import com.itboye.ihomebank.web.WebActivity;

import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.util.SPUtils.getSp;

/**
 * Created by Administrator on 2017/4/14.
 */

public class ActivityHuajKuanPay extends BaseOtherActivity implements Observer {
    View v_statusbar;
    ImageView zhifubao_selectBtn, yue_selectBtn, xiaotong_selectBtn;
    HuanKuansBean.Plan plan;
    TextView benqi, go_pay, txt_xiaotong;
    JinRongPresenter jinRongPresenter;
    private boolean isZfb = true;
    MyApplcation myApp;
    private boolean isXiaoTong;
    private CharSequence fenQiCount;
    ImageView close_icon;
    UserPresenter userPresenter;
    private EditText editText;
    @Override
    protected int layout_id() {
        return R.layout.activity_pay_huankuan;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        myApp = (MyApplcation) getApplication();
        jinRongPresenter = new JinRongPresenter(this);
        zhifubao_selectBtn.setBackgroundResource(R.drawable.select);
        yue_selectBtn.setBackgroundResource(R.drawable.unselect);
        xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
        plan = (HuanKuansBean.Plan) getIntent().getSerializableExtra("model");
        userPresenter = new UserPresenter(this);
        benqi.setText(DoubleUtil.doubleTransform(plan.getTotal()) + "元");

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.yue_selectBtn:
                isZfb = false;
                isXiaoTong = false;
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.select);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                txt_xiaotong.setText("小通分期");
                break;
            case R.id.zhifubao_selectBtn:
                isXiaoTong = false;
                isZfb = true;
                zhifubao_selectBtn.setBackgroundResource(R.drawable.select);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
                txt_xiaotong.setText("小通分期");
                break;
            case R.id.xiaotong_selectBtn:
                setXiaoTong();
                break;
            case R.id.go_pay:
                if (isZfb) {
                    //支付宝支付
                    jinRongPresenter.sendJinRongPay(getSp(SPContants.USER_ID), "loan", plan.getItem(), "6325", "", "0", "");
                } else {
                    if (isXiaoTong) {
                        //小通
                        jinRongPresenter.sendJinRongPay(getSp(SPContants.USER_ID), "loan", plan.getItem(), "6428", "", "0", "");
                    } else {
                        AlertDialog.Builder alert = new AlertDialog.Builder(this);
                        alert.setTitle("提示信息");
                        editText = new EditText(this);
                        editText.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
                        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        editText.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
                        editText.setHint("请输入支付密码");
                        alert.setView(editText);
                        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String psw = editText.getText().toString();
                                if (psw.equals("")) {
                                    ByAlert.alert("请输入支付密码");
                                    return;
                                }
                                userPresenter.ZhiFuPassYanZheng(getSp(SPContants.USER_ID), psw);
                            }
                        });
                        alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        alert.create();
                        alert.show();
                        //余额支付
//                        jinRongPresenter.sendJinRongPay(getSp(SPContants.USER_ID), "loan", plan.getItem(), "6325", (plan.getPrincipal() + plan.getAccrual()) + "", "1", "");
                    }
                }
                break;
            case R.id.close_icon:
                finish();
                break;
        }
    }

    int position = -1;
    CharSequence[] xiaoTongItems = {"3", "6", "12"};

    private void setXiaoTong() {
        position = -1;
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("选择分期数");
        alert.setSingleChoiceItems(xiaoTongItems, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                position = which;
            }
        });
        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (position == -1) {
                    position = 0;
                }
                isXiaoTong = true;
                isZfb = false;
                zhifubao_selectBtn.setBackgroundResource(R.drawable.unselect);
                yue_selectBtn.setBackgroundResource(R.drawable.unselect);
                xiaotong_selectBtn.setBackgroundResource(R.drawable.select);
                fenQiCount = xiaoTongItems[position];
                txt_xiaotong.setText("小通分期(" + xiaoTongItems[position] + "期)");
            }
        });
        alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alert.create();
        alert.show();

    }

    /**
     * 支付宝
     */
    private void zfb(PayInfo bean) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        String money = bean.getTotalPrice();
        double m = Double.parseDouble(money) / 100;
        String content = bean.getName();
        String code = bean.getCode();
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(SPContants.APPID, m + "", content, code, TimeFormat.getSimData());
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, SPContants.RSA_PRIVATE);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ActivityHuajKuanPay.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ByAlert.alert("支付成功");
                        startActivity(new Intent(ActivityHuajKuanPay.this, HuanKuanResult.class));
                        myApp.HuanKuanDetailUI.finish();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ByAlert.alert("支付失败");
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void update(Observable observable, Object data) {
        try {
            closeProgressDialog();
        }catch (Exception e){

        }
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (!entity.getCode().equals("0")) {
                ByAlert.alert(entity.getMsg());
                return;
            }
            if (entity.getEventType() == JinRongPresenter.sendJinRongPay_success) {
                PayInfo payInfo = (PayInfo) entity.getData();
                if (payInfo != null) {
                    if (isZfb) {
                        zfb(payInfo);
                    } else {
                        if (isXiaoTong) {
                            Intent intent = new Intent(this, WebActivity.class);
                            ///ulinkpay/pay/pay_code/(支付号)/pay_nper/(分期期数)
                            System.out.println("支付链接"+NetPublicConstant.URL + "/ulinkpay/pay/pay_code/" + payInfo.getCode() + "/pay_nper/" + fenQiCount.toString());
                            intent.putExtra("url", NetPublicConstant.URL + "/ulinkpay/pay/pay_code/" + payInfo.getCode() + "/pay_nper/" + fenQiCount.toString());
                            startActivity(intent);
//                            finish();
                            return;
                        }
                        if (payInfo.getPaySuccess().equals("1")) {
                            ByAlert.alert("支付成功");
                            startActivity(new Intent(ActivityHuajKuanPay.this, HuanKuanResult.class));
                            myApp.HuanKuanDetailUI.finish();
                            finish();
                        }
                    }
                }
            } else if (entity.getEventType() == JinRongPresenter.sendJinRongPay_fail) {
                ByAlert.alert(entity.getData());
            }else if (entity.getEventType() == UserPresenter.zhiFuPassYanZheng_success) {
                showProgressDialog("正在支付中,请稍后",true);
                jinRongPresenter.sendJinRongPay(getSp(SPContants.USER_ID), "loan", plan.getItem(), "6325", "", "1", "");
            }else if (entity.getEventType() == UserPresenter.zhiFuPassYanZheng_fail) {
                ByAlert.alert(entity.getData());
            }
        }
    }
}
